// pages/data/user/user.js
import { apiClient, apiRoutes } from "../../../utils/api";
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orgid: null,
    orgname: null,
    lists:[], //{'tablename':'devices','items':[]}
    user:{}, //{id: 1, username: "Henry", devices: Array(3)} | {device_name: "传感器", tablename: "devices", items: Array(2)}
    id: 0,
    name: "",
    password: "",
    role: "",
    orgs: app.globalData.orgs,
    equipment: { "devices": [], "switches": [], "cameras": [] },
    selectedIds: { "devices": [], "switches": [], "cameras": [] },
    equipmentTypes: ['devices', 'switches', 'cameras']
  },

  /**
   * 生命周期函数
   */
  async onLoad(options) {
    let id, name,role;
    if (options.id == 0){
      id = 0
      name = ''
      role = ''
    } else {
      id = app.globalData.user.id, 
      name = app.globalData.user.username,
      role = app.globalData.user.role
    }
    this.setData({ 
      orgid: app.globalData.orgid,
      orgname: app.globalData.orgname,
      lists:app.globalData.lists, 
      user:app.globalData.user, 
      id: id, 
      name: name,
      role: role
    });
    // console.log(this.data.role, app.globalData.role)
    console.log("onload lists",this.data.lists)
    if (options.id == 0) return
    this.init_checked_in_lists()
  },
  init_checked_in_lists() {
    const newlists = this.data.lists.map(list => {
      const newItems = list.items.map(item => {
        const exist = item.users.find(user => user.id === this.data.id);
        return {
          ...item,
          checked: !!exist  // 转成布尔值 true / false
        };
      });
  
      return {
        ...list,
        items: newItems
      };
    });
    
    // 更新lists数据
    this.setData({lists: newlists});
    
    // 根据新的checked状态更新selectedIds
    const selectedIds = {
      devices: [],
      switches: [],
      cameras: []
    };
    
    newlists.forEach(list => {
      const type = list.tablename;
      selectedIds[type] = list.items
        .filter(item => item.checked)
        .map(item => item.id);
    });
    
    this.setData({ selectedIds });
    console.log("Initial selectedIds:", this.data.selectedIds);
  },
  
  /**
   * 格式化设备数据
   */
  async formatEquipmentData() {
    const { lists } = app.globalData;
    const userDevices = app.globalData.user.devices || [];
    
    // 获取用户拥有的所有设备ID
    const userDeviceIds = {
      devices: this.getUserDeviceIds(userDevices, 'devices'),
      switches: this.getUserDeviceIds(userDevices, 'switches'),
      cameras: this.getUserDeviceIds(userDevices, 'cameras')
    };

    // 格式化设备数据
    const equipment = {};
    lists.forEach(list => {
      const type = list.listname;
      equipment[type] = list.items.map(item => ({
        ...item,
        checked: userDeviceIds[type].includes(item.id)
      }));
    });

    this.setData({ equipment });
  },

  /**
   * 获取用户拥有的某类设备ID数组
   */
  getUserDeviceIds(userDevices, type) {
    const deviceList = userDevices.find(d => d.tablename === type);
    return deviceList ? deviceList.items.map(item => item.id) : [];
  },

  /**
   * 初始化选中的设备ID
   */
  initSelectedIds() {
    const { equipment } = this.data;
    const selectedIds = {
      devices: equipment.devices.filter(item => item.checked).map(item => item.id),
      switches: equipment.switches.filter(item => item.checked).map(item => item.id),
      cameras: equipment.cameras.filter(item => item.checked).map(item => item.id)
    };

    this.setData({ selectedIds });
  },

  /**
   * 创建用户
   */
  async createUser() {
    const { name, password, role } = this.data;
    
    if (!name || !password) {
      wx.showToast({
        title: '用户名和密码不能为空',
        icon: 'error'
      });
      return;
    }

    try {
      const response = await apiClient.post(apiRoutes.users, {
        username: name,
        password,
        organization: app.globalData.orgid,
        role
      });

      if (response.data.id) {
        this.setData({ id: response.data.id });
        await this.bindUserEquipment(response.data.id);
        wx.showToast({ title: '新增人员成功' });
        wx.navigateBack();
    } else {
        throw new Error('新增人员失败');
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '新增人员失败',
        icon: 'error'
      });
    }
  },

  /**
   * 更新用户信息
   */
  async updateUser() {
    const { id, name, password, role } = this.data;
    
    if (!id) return;

    try {
      const url = `${apiRoutes.users}${id}/`;
      const data = { username: name, role };
      if (password) data.password = password;

      await apiClient.patch(url, data);
      await this.bindUserEquipment();
      
      wx.showToast({ title: '修改成功' });
      wx.navigateBack();
    } catch (error) {
      wx.showToast({
        title: '修改失败',
        icon: 'error'
      });
    }
  },

  /**
   * 绑定用户设备
   */
  async bindUserEquipment(userId = this.data.id) {
    if (!userId) return;

    try {
      const response = await apiClient.put(
        `${apiRoutes.users}${userId}/update_devices/`,
        this.data.selectedIds
      );

      if (response.statusCode === 200) {
        console.log('设备绑定成功');
      }
    } catch (error) {
      console.error('设备绑定失败:', error);
    }
  },

  /**
   * 角色选择变化
   */
  handleRoleChange(e) {
    this.setData({ role: e.detail.value });
  },

  /**
   * 设备选择变化
   */
  handleEquipmentSelectionChange(e) {
    const { value: selectedIds } = e.detail;
    const { type } = e.currentTarget.dataset;
    
    this.setData({ 
      [`selectedIds.${type}`]: selectedIds 
    });
    console.log(this.data.selectedIds)
  }
});